﻿Imports SKYPE4COMLib
Imports ChatterBotAPI
Imports System.Threading
Imports System.IO
Public Class Form1
    Public Skype As New Skype

    Public factory As ChatterBotFactory = New ChatterBotFactory()

    Public jabber As ChatterBot = factory.Create(ChatterBotType.JABBERWACKY)
    Public jabbersession As ChatterBotSession = jabber.CreateSession()

    Public chatter As ChatterBot = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477")
    Public chattersession As ChatterBotSession = chatter.CreateSession

    Public CurrentBot As Integer = 1

    Public Log As System.Threading.Thread = New System.Threading.Thread(AddressOf Chatt)

    Public MessageUser As String
    Public MessageBot As String

    Public AuthedUser As String

    Public CurrTime As String

    Public ShouldReply As Boolean = True

    Dim Threadd As Thread

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        If Skype.Client.IsRunning = False Then
            Skype.Client.Start()                'Starting the Skype client if it is not already running.
            System.Threading.Thread.Sleep(60000) 'Waiting 60 seconds, because Skype needs to fully start before we can connect, and Skype is slow.
        End If                                        'This delay also allows skype to download new messages so that the bot won't spam group conversations.

        Skype.Attach(7, True) 'Connecting to Skype

        CheckForIllegalCrossThreadCalls = False             'Cross thread Calls :D
        'AddHandler Skype.Calls, AddressOf Skype_call
        AddHandler Skype.MessageStatus, AddressOf Skype_MessageStatus       'Detects new Skype messages forwards them.
        AddHandler Skype.UserAuthorizationRequestReceived, AddressOf AddFriend 'Detects new Friend Request and Authorises it.
        Threadd = New Thread(AddressOf Skype_call) 'Doesn't do anything atm, I want it to auto-cancel calls.
            Threadd.IsBackground = True
            Threadd.Start()
    End Sub

    Private Sub Skype_call()
        'See? Nothing.
    End Sub

    Private Sub AddFriend(ByVal user As SKYPE4COMLib.User)
        user.IsAuthorized = True 'Adds Friends when they Add me :D
    End Sub

    Private Sub Skype_MessageStatus(ByVal msg As ChatMessage, ByVal status As TChatMessageStatus)
        CurrTime = (System.DateTime.Now) 'Getting the Current time regardless of weather a new message was recieved.
        If status = TChatMessageStatus.cmsReceived Then  'New Message :D
            If msg.Body.StartsWith("!") And Not msg.Body.EndsWith("!") Then 'Checking if it is a Command, Denoted as a '!'
                Dim CommandStatus As Boolean 'If a command runs, this becomes True so that the help message isn't shown.
                msg.Chat.SendMessage("Command Recieved, Processing...")
                RichTextBox1.AppendText("Recieved Command. It was: " & msg.Body & vbNewLine)
                If msg.Body.ToLower = "!Help".ToLower Then              'Help Command
                    msg.Chat.SendMessage("You can use the following commands:" & vbNewLine & _
                                         "!help" & vbNewLine & _
                                         "!authenticate" & vbNewLine & _
                                         "!deauth" & vbNewLine & _
                                         "!IsAuthed" & vbNewLine & _
                                         "!bot1 to talk to Jabber" & vbNewLine & _
                                         "!bot2 to talk to Chatter" & vbNewLine & _
                                         "If you have any requests, please message Krutonium")
                    CommandStatus = True
                End If
                If msg.Body.ToLower.StartsWith("!Authenticate".ToLower) Then
                    If File.Exists("C:\Password.ini") = False Then
                        File.Create("C:\Password.ini")
                        System.Threading.Thread.Sleep(500)
                    Else
                        If File.ReadAllText("C:\Password.ini") = "ExamplePass" Then
                            RichTextBox1.AppendText("YOU ARE USING THE DEFAULT PASSWORD! YOU NEED TO CHANGE THIS! {C:\Password.ini}" & vbNewLine)
                        End If
                    End If

                    'Dim CurrentPassword = File.ReadAllText("C:\Password.ini")
                    Dim CurrentPassword As String = "Boadway1"
                    If msg.Body.EndsWith(CurrentPassword) Then
                        msg.Chat.SendMessage("User Authenticated.")
                        AuthedUser = msg.Sender.DisplayName             'This Code does nothing but confirm a Password, you can add
                        CommandStatus = True                    'things like Admin Only Commands that check against this if you want.
                    Else
                        msg.Chat.SendMessage("Syntax is !Authenticate [Password]" & vbNewLine & _
                                             "If you don't have a password, please don't try to authenticate.") 'Password is Wrong.
                        CommandStatus = True
                    End If
                End If
                If msg.Body.ToLower = ("!bot1".ToLower) Then
                    CurrentBot = 1
                    msg.Chat.SendMessage("Switched to Jabber")  'Switches to Bot1
                    CommandStatus = True
                End If
                If msg.Body.ToLower = ("!bot2".ToLower) Then
                    CurrentBot = 2
                    msg.Chat.SendMessage("Switched to Chatter") 'Switches to Bot2
                    CommandStatus = True
                End If

                If msg.Body.ToLower = "!Stop".ToLower And msg.Sender.DisplayName = AuthedUser Then  'An Example command for Remotly stopping the bot ONLY IF AUTHENTICATED
                    ShouldReply = False
                    msg.Chat.SendMessage("Stopped Replying to Messages")
                    CommandStatus = True
                End If

                If msg.Body.ToLower = "!Start".ToLower And msg.Sender.DisplayName = AuthedUser Then
                    ShouldReply = True
                    msg.Chat.SendMessage("Started Replying to Messages")
                    CommandStatus = True
                End If

                If msg.Body.ToLower = "!Deauth".ToLower And msg.Sender.DisplayName = AuthedUser Then
                    AuthedUser = Nothing
                    msg.Chat.SendMessage("Successfully Deauthed!")
                    CommandStatus = True
                End If

                If msg.Body.ToLower = "!IsAuthed".ToLower Then
                    If msg.Sender.DisplayName = AuthedUser Then
                        msg.Chat.SendMessage("You are Authenticated")
                    Else
                        msg.Chat.SendMessage("You are Not Authenticated")
                    End If
                    CommandStatus = True
                End If

                If msg.Body.ToLower = "!IP".ToLower Then
                    If msg.Sender.DisplayName = AuthedUser Then
                        Dim hostName = System.Net.Dns.GetHostName()
                        For Each hostAdr In System.Net.Dns.GetHostEntry(hostName).AddressList()
                            If hostAdr.ToString().StartsWith("192.168.") Then   'For getting the IP of the Bot on LAN.
                                msg.Chat.SendMessage(hostAdr.ToString)
                            End If
                        Next
                    Else
                        msg.Chat.SendMessage("You need to !Authenticate First!")
                    End If
                    CommandStatus = True
                End If

                If CommandStatus = False Then
                    msg.Chat.SendMessage(msg.Body & " is not a valid command.") 'No Command was Valid, so Help is Displayed.
                    msg.Chat.SendMessage("Perhaps you meant '!Help'?")
                End If
                'If msg.Body.ToLower.StartsWith("!SendMessageToAll".ToLower) Then
                'Dim Users As Array = Skype.Friends.OfType(Of User)()
                'MsgBox(Users)
                'End If

            Else
                'This Section takes the Users Message, Forwards it to the bot, and then from that, sends it back to the user.
                If ShouldReply = True Then
                    If CurrentBot = 1 Then
                        Try
                            MessageUser = msg.Body
                            'RichTextBox1.AppendText(msg.Sender.ToString & " " & msg.Body & vbNewLine)
                            MessageBot = jabbersession.Think(msg.Body)
                            msg.Chat.SendMessage(MessageBot)
                            RichTextBox1.AppendText(CurrTime & " " & msg.Sender.FullName & ": " & msg.Body & vbNewLine)  'Logging
                            RichTextBox1.AppendText(CurrTime & " " & "Jabber: " & MessageBot & vbNewLine)
                            'Beep()
                        Catch ex As Exception
                            msg.Chat.SendMessage("This AI appears to have Crashed. We apologise for this inconvenience." & vbNewLine & "Switching to Bot 2...")
                            RichTextBox1.AppendText(CurrTime & " " & ex.ToString & vbNewLine)                      '^This is me.
                            CurrentBot = 2
                            'Beep()
                            'System.Threading.Thread.Sleep(500)
                            'Beep()
                        End Try
                    End If
                    If CurrentBot = 2 Then
                        Try
                            MessageUser = msg.Body
                            'RichTextBox1.AppendText(msg.Sender.ToString & " " & msg.Body & vbNewLine)
                            MessageBot = chattersession.Think(msg.Body)
                            msg.Chat.SendMessage(MessageBot)
                            RichTextBox1.AppendText(CurrTime & " " & msg.Sender.FullName & ": " & msg.Body & vbNewLine)
                            RichTextBox1.AppendText(CurrTime & " " & "Chatter: " & MessageBot & vbNewLine)
                            'Beep()
                        Catch ex As Exception
                            msg.Chat.SendMessage("This AI appears to have Crashed. We apologise for this inconvenience." & vbNewLine & "Switching to Bot 1...")
                            RichTextBox1.AppendText(CurrTime & " " & ex.ToString & vbNewLine)
                            CurrentBot = 1
                            'Beep()
                            'System.Threading.Thread.Sleep(500)
                            'Beep()
                        End Try
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub cmdStart_Click(sender As System.Object, e As System.EventArgs) Handles cmdStart.Click
        AddHandler Skype.MessageStatus, AddressOf Skype_MessageStatus 'Don't click this multiple times, or you will have issues.
    End Sub

    Private Sub cmdStop_Click(sender As System.Object, e As System.EventArgs) Handles cmdStop.Click
        RemoveHandler Skype.MessageStatus, AddressOf Skype_MessageStatus 'Click this all you want, it will stop the bot responding to everything - including commands.
    End Sub

    Private Sub Chatt()
    End Sub

    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
        Do Until Skype.ConnectionStatus = TConnectionStatus.conOnline
            Try
                Skype.Attach(7, True)           'Not Used, as it has been seen to cause crashes.
            Catch ex As Exception
                'MsgBox(ex.ToString)
            End Try
        Loop
    End Sub
End Class

